import { ref, reactive, Ref, computed } from 'vue'
import Project from '../types/Project';
import { MemberViewModel, emptyMemberViewModel } from '../types/Member';
import axios from '@/axios';
import app from '@/app';

const BEN_KE_SHENG = "本科生";
/**
 * 生成用以申请表的视图模型
 * @param proj 缓存的项目
 * @param role 学工号对应的角色
 * @param maxCapacity 此数组长度的最大值
 * @returns 
 */
export function useMembers(proj: Project, role: string, maxCapacity: number) {
    function reset () {
        let init : MemberViewModel[] = role === BEN_KE_SHENG ? proj.toStudentsMemberViewModel() : proj.toTeachersMemberViewModel();
        members.value = [...init];
    }

    const members: Ref<MemberViewModel[]> = ref([]);
    const errorStrings: Ref<string[]> = ref([]);
    const canCreate = computed(() => members.value.length < maxCapacity);
    reset();   

    async function getUserByCode(item: MemberViewModel): Promise<MemberViewModel> {
        let msg = await axios.post("/api/proj/common/GetUserByCode", { code: item.code, role });
        let member: MemberViewModel = { ...msg.data };
        item.code = member.code;
        item.department = member.department;
        item.realName = !!member.code ? member.realName : `找不到该${role === BEN_KE_SHENG ? "学" : "工"}号`;
        item.major = member.major;
        item.reformType = member.reformType;
        return member;
    }

    async function validate(): Promise<boolean> {
        errorStrings.value = [];
        members.value = members.value.filter(e => e.code && e.realName);

        let order = 1;
        let codes: string[] = [];
        for (let item of members.value) {
            item.memberOrder = order++;
            if (item.memberOrder === 1 && role === BEN_KE_SHENG && app.currentUser.currentRole.Name === BEN_KE_SHENG && app.currentUser.Code !== item.code) {
                // 本科生自己填写项目时，第一位必须是自己
                errorStrings.value.push("成员的第一位必须是自己，并且必须是负责人");
                return false;
            }

            if (codes.indexOf(item.code) > -1) {
                errorStrings.value.push(`${item.realName} / ${item.code} 出现了多次，请检查`);
                return false;
            }

            if (item.division.length > 50) {
                errorStrings.value.push(`${item.realName}的分工字段多于50字，请修改`);
                return false;
            }

            codes.push(item.code);
        }

        if (members.value.length === 0) {
            errorStrings.value.push(`至少包含一位${role !== BEN_KE_SHENG ? "指导老师" : "成员"}`);
            return false;
        }

        if (members.value.length > maxCapacity) {
            errorStrings.value.push(`不能超过${maxCapacity}人`);
            return false;
        }

        return true;
    }

    async function createEmpty() {
        members.value.push({ ...emptyMemberViewModel });
        reorderItem();
    }

    function removeItem (index: number): MemberViewModel[] {
        var removed = members.value.splice(index, 1);
        reorderItem();
        return removed;
    }

    function moveUp (index: number) {
        // 如果index == 1, 则必须判断有没有权限将当前用户改为负责人
        if (index === 1) {
            // 判断权限，如果此人是学生，就不可以上移
            if (role === BEN_KE_SHENG && app.currentUser.currentRole.Name === BEN_KE_SHENG) {
                // 本科生不可以修改负责人字段
                return;
            }

            // 反之，将元素移上去时，需要将第1位的那个改为负责人
            members.value[0].division = "";
            members.value[1].division = "负责人";
            internalMoveUp(index);
        } else if (index > 0 && index < members.value.length) {
            internalMoveUp(index);
        }
    }

    function moveDown (index : number) {
        // 如果index == 0, 则必须判断有没有权限将当前用户改为负责人
        if (index === 0) {
            // 判断权限，如果此人是学生，就不可以下移
            if (role === BEN_KE_SHENG && app.currentUser.currentRole.Name === BEN_KE_SHENG) {
                // 本科生不可以修改负责人字段
                return;
            }

            // 反之，将元素移上去时，需要将第1位的那个改为负责人
            members.value[0].division = "";
            members.value[1].division = "负责人";
            internalMoveDown(index);
        } else if (index > 0 && index < members.value.length - 1) {
            internalMoveDown(index);
        }
    }

    // 上移
    function internalMoveUp (index: number) {
        let array = members.value;
        [array[index], array[index - 1]] = [array[index - 1], array[index]]
        members.value = [...array];
        reorderItem();
    }
    // 下移
    function internalMoveDown (index: number) {
        let array = members.value;
        [array[index], array[index + 1]] = [array[index + 1], array[index]]
        members.value = [...array];
        reorderItem();
    }

    function reorderItem () {
        let order = 1;
        for (let item of members.value) {
            item.memberOrder = order++;
        }
    }

    return {
        members,
        getUserByCode,
        errorStrings,
        createEmpty,
        validate,
        removeItem,
        moveUp,
        moveDown,
        reset,
        canCreate
    }
}

export default useMembers;